package net;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import utils.Config;

public class TCPServerStarter implements Runnable {
    
    private static final Logger logger = LogManager.getLogger(TCPServerStarter.class);
    
    private Config config;

    public TCPServerStarter(Config config) {
        this.config = config;
    }



    @Override
    public void run() {
        ExecutorService executor = Executors.newCachedThreadPool();
        try(ServerSocket serverSocket = new ServerSocket(config.getPort());){
            while(true){//本次TCP连接传输完，重新建立TCPListener在端口上继续监听
                Socket incoming = serverSocket.accept();
                executor.execute(new TCPListener(config,incoming));
                //executor.shutdown();//如果不屏蔽，程序只能接收1个线程，启动第2个线程时，提示RejectedExecutionException
            }
            
        } catch (IOException e) {
            logger.error("Exception:"+e+" Strat failed! Port: "+config.getPort()+" Type:"+config.getPortType());
            executor.shutdown();
           
        }
        

    }

}
